(function(E){
/*
 基础插件：
 Redo, Undo
 Font
 Image
 Link
 ForeColor,BackColor
 Source,PasteText
 PasteWord
 Save
 AutoHeight
*/

E.plugin("Redo,Undo", {
	type:'base', //声明为没有面板的基础插件
	
	require:{//此插件依赖哪些模块和插件
		mod:['history'],
		plugin:[]
	},
	
	click:function($btn, dom, eid){
		var name=this.name, History=E.mod("History"),Toolbar=E.mod("Toolbar"),
			Confirm=E.mod('Confirm');
		if (History){
			History[name]($btn, dom, eid);
		}else{
			E.execCommand(name);
		}
		Toolbar.blur($btn, eid);
		
		//设置或取消离开提示
		History.pointer[eid] == 0?Confirm.clear():Confirm.set();
		
		var option=E.options[eid], AutoHeight=E.plugin("AutoHeight");
		if (option.autoHeight && AutoHeight){
			AutoHeight(eid);
		}
		return 1;
	}
});

E.plugin("Font", {
	config:{
		left:1,
		width:300,
		Font:[
			{name:'宋体',
			value:'SimSun'},		'Georgia',
			{name:'仿宋体',
			value:'FangSong_GB2312'},'Times New Roman',
			{name:'微软雅黑',
			value:'Microsoft YaHei'},'Impact',
			{name:'黑体',
			value:'SimHei'},		'Courier New',
			{name:'楷体',
			value:'楷体_GB2312'},	'Arial',
			'Verdana',    			'Tahoma'
		],
		FontSize:{
              "10"   : "2",
              "12"   : "3",
              "14"   : "4",
              "18"   : "5",
              "24"   : "6",
              "36"   : "7"
		}
	},
	
	getFont:function(){
		var html=[], list=this.config.Font,font, name;
		
		for(var i=0; i<list.length; i++){
			if(typeof list[i] == "string"){
				font=list[i];
				name=list[i];
			}else if (typeof list[i] == "object"){
				font=list[i].value;
				name=list[i].name;
			}
			
			html.push('<a href="javascript:void(\''+font
			+'\')" style="font-family: '+font+'" font="'+font+'">'+name+'</a>');
		}
		return html.join('');
	},
	
	getFontSize:function(){
		var html=[], list=this.config.FontSize;
		
		for(var i in list){
			html.push('<a href="javascript:void(\''+list[i]
			+'\')" style="font-size:'+i+'pt">'+i+'</a>');
		}
		
		return html.join('');
	},
	
	/*
	初始化一些dom操作，以提高点击按钮后的响应速度
	*/
	init:function(){
		this.cache['html']='<fieldset class="font">'
			+'<legend>字体</legend>'
			+ this.getFont()
			+'</fieldset>'
			+'<fieldset class="fontsize">'
			+'<legend>大小</legend>'
			+ this.getFontSize()
			+'</fieldset>';
	},
	
	/*
	
	*/
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 插件的名称
		var self=this, name=this.name, html=this.cache['html'], Panel=E.mod("Panel"), $P;
		$P=Panel.show(html, eid, self);
		
		$P.find("a").unbind('click').click(function(i){
			self.setFont(this, Panel);
			Panel.hide($btn);
		});
		return 1;
	},
	
	setFont:function(el){
		var eid=E.eid, value=$(el).text(),History=E.mod("History"), dom=this['dom'];
		if(/^\d+$/.test(value)){
			value = this.config.FontSize[value];
			E.execCommand('FontSize', false, value);
		}else{
			value=$(el).attr("font");
			E.execCommand('FontName', false, value);
		}
		History && History.add(dom, eid);
	}
});


E.plugin("Image", {
	config:{
		width:400,
		uploadUrl:''
	},
	
	init:function(){
		this.cache['html']='<form onsubmit="return false"><table border="0" width="100%">'
			+'<tr><td width="75">图片地址：</td>'
			+'<td height="25" align="left">'
			+'<input type="text" value="http://" style="width:230px;" name="src" maxlength="250"/>'
			+'</td>'
	
			+'<td align="left"><select title="图片的对齐方式" name="align" style="width:80px;height:21px;">'
			+'<option value="left">左对齐</option>'
			+'<option value="middle">居中</option>'
			+'<option value="right">右对齐</option></select>'
			+'</td></tr>'

			+'<tr><td>图片连接：</td>'
			+'<td height="25" align="left">'
			+'<input type="text" value="" style="width:230px;" name="url" maxlength="200"/>'
			+'</td>'
			
			+'<td align="left"><select title="打开图片链接的方式" name="target" style="width:80px;height:21px;">'
			+'<option value="_blank" selected>新窗口</option>'
			+'<option value="_self">当前窗口</option></select>'
			+'</td></tr>'
			
			+'</table></form>';
	},
	
	/*
	
	*/
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 插件的名称
		var self=this, name=this.name, html=this.cache['html'],
			content='', $P, Data=E.mod("Data"), Panel=E.mod("Panel");
		
		if(name =='Source' && Data){content=Data.get(eid);}
		$P = Panel.show(html, eid, self);
		/*
		var text='', Selection=E.mod("Selection");
		if(Selection) text=Selection.get();
		$P.find("input[name=text]").val(text);
		*/
		return 1;
	},
	
	ok: function(eid, Data){
		var self=this, eid=eid||E.eid, html='', name=this.name, Panel=E.mod("Panel");
		var v = Panel.getInputsValue(eid, name);
		
		if(!/.*?\.(jpg|gif|png)/i.test(v.src)){
			return 1;
		}
		
		html = '<img src="'+v.src+'" align="'+v.align+'" border="0"/>';
		
		if(v.url){
			html = '<a href="'+v.url+'" target="'+v.target+'">'+html+'</a>';
		}
		
		Data.insertHtml(html);// 将插入的内容不经过 escape
		return 1;
	}
});

E.plugin("Link", {
	config:{
		width:300
	},
	
	init:function(){
		this.cache['html']='<form onsubmit="return false"><table border="0" width="100%">'
			+'<tr><td>文 字：</td>'
			+'<td height="25" align="left">'
			+'<input type="text" value="" style="width:240px;" name="text" maxlength="200"/>'
			+'</td></tr>'
			
			+'<tr><td width="50">网 址：</td>'
			+'<td height="25" align="left">'
			+'<input type="text" value="http://" style="width:240px;" name="url" maxlength="250"/>'
			+'</td></tr>'
			
			+'<tr><td>打 开：</td><td align="left"><select name="target">'
			+'<option value="_blank">在新窗口(target=_blank)</option>'
			+'<option value="_self">在本窗口</option></select>'
			+'</td></tr>'
			
			+'</table></form>';
	},
	
	/*
	
	*/
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 插件的名称
		var self=this, name=this.name, html=this.cache['html'],
			Panel=E.mod("Panel"),$P;		

		$P=Panel.show(html, eid, self);
		
		var text='', Selection=E.mod("Selection");
		if(Selection) text=Selection.get();
		$P.find("input[name=text]").val(text);
		return 1;
	},
	
	ok: function(eid, Data){
		//name 插件的名称
		var self=this, eid=eid||E.eid, html='', name=this.name, Panel=E.mod("Panel");
		var v = Panel.getInputsValue(eid, name);
		v.text = v.text || v.url;
		
		html = '<a href="'+v.url+'" target="'+v.target+'">'+v.text+'</a>';
		Data.insertHtml(html);
		return 1;
	}
});

E.plugin("ForeColor,BackColor", {
	color:[], //当前选中的颜色，键值是eid
	config:{
		//下拉面板的宽度和高度
		width:208,
		height:160
	},
	
	colors:{
		'default':[
			'000000,993300,333300,003300,003366,000080,333399,333333',
			'800000,FF6600,808000,008000,008080,0000FF,666699,808080',
			'FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999',
			'FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0',
			'FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF'
		]
	},
	
	init:function(){
		this.cache['html']=this.getHtml();
	},
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 是插件的名称
		var self=this, name=this.name;
		
		if(self.color[eid]){
			var color=self.color[eid];
			self.setColor(color);
		}
		return 1;//click 函数需要返回 1 或 0
	},
	menu:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 是插件的名称
		var self=this, name=this.name, html=this.cache['html'],Panel=E.mod("Panel"),$P;
		$P=Panel.show(html, eid, self);
		
		$P.find("span.color").unbind('click').click(function(){
			var color='#'+$(this).attr('name');
			self.color[eid]=color;
			
			self.setColor(color);
			Panel.hide($btn);
		});
		
		return 1;//click 函数需要返回 1 或 0
	},
	setColor:function(color){
		var eid=this['eid'], dom = this['dom'], $btn = this["$btn"], History=E.mod("History");
		
		E.execCommand(this.name, false, color);
		$btn.find("a.img").css("background", color);
		History && History.add(dom, eid);
		
	},
	
	getHtml:function(name){
		var html=[],a,span,colors,c,list;
		list = this.colors[name] || this.colors['default'];
		a='<a href="javascript:void(\'#000\')" '
			+'style="width:16px;height:16px;background:#000"></a>';
		
		span='<span class="color" name="Transparent" style="width:206px;height:24px;">'+a
			+'自 动</span>';
		html.push(span);
		for(var i=0;i<list.length;i++){
			colors = list[i].split(",");
			for(var j=0;j<colors.length;j++){
				c=colors[j];
				a='<a href="javascript:void(\'#'+c+'\')" '
					+'style="width:16px;height:16px;background:#'+c+'"></a>';
				
				span='<span class="color" name="'+c+'" style="width:24px;height:24px;">'+a+'</span>';
				
				html.push(span);
			}
		}
		
		return html.join('');
	}
});

E.plugin("Source,PasteText", {
	config:{
		width:600,
		height:270
	},
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		//name 插件的名称
		var self=this, name=self.name, html='', Data=E.mod("Data"),
			content='', id=eid+'_'+name+'_content',Panel=E.mod("Panel");
		
		/*
		注意：
		不能把内容直接拼到字符串里面，这样的话内容里面的 &lt; &gt; 等会变成 < >  从而导致内容错误。
		必须采用赋值的方式。
		html='<textarea id="'+id+'" style="width:99%;height:99%">'+content+'</textarea>';
		*/
		html='<div name="tip"></div><textarea id="'+id+'" style="width:99%;height:99%"></textarea>';
		self.panel=Panel.show(html, eid, self);
		var textarea = $("#"+id);
		
		//对于IE6， textarea 的style.height=100% 好像不起作用，故设置一个固定值
		if($.IE6 || $.IE7){
			textarea.height(textarea.parent("div").height());
		}
		
		setTimeout(function(){
			if(name =='Source' && Data){
				content=Data.get(eid);
				if(content){textarea.val(content);}
			}
			textarea.focus();
		}, 100);
		return 1;
	},
	
	/**
	name 插件的名称，这里不必执行隐藏面板的操作
	*/
	ok: function(eid, Data){
		var self=this, name=self.name, content=$("#"+eid+'_'+name+'_content').val();
		//需要对内容做标签校验
		
		if(name =='Source'){
			var tip=Data.checkTag(content);
			if(!tip){
				Data.set(content);
			}else{
				//self.panel.find('div[name=tip]').html(tip);
				alert(tip);
				return 0;//不关闭当前面板
			}
		}else if (name =='PasteText'){
			Data.insertText(content);
		}
		return 1;
	}
});

/**
 * 过滤从 word 粘贴的数据
 * Ref: CKEditor - pastefromword plugin
 */
E.plugin("PasteWord", {
	iframe:null,
	_dom:null, //插件自己的iframe dom对象
	defaultHtml:'<p>&nbsp;</p>',
	config:{
		width:600,
		height:270
	},
	click:function($btn, dom, eid){
		this.set($btn, dom, eid);
		var self=this, name=self.name,Data=E.mod("Data"), html='', Panel=E.mod("Panel");
		$P = Panel.show(html, eid, self);
		
		setTimeout(function(){
			var html="", options=E.options[eid], $container=$P.find("div.panel_body");
			if($container.find("iframe").size()==0) {
				
				var iframe = E.iframe(options, $container[0], self.defaultHtml);
				html='请将Word当中的内容粘贴到这里，然后点击下面的确定按钮，Word当中的样式将被过滤。';
				$(iframe).before('<div style="text-align:left;line-height:22px;">'+html+'</div>');
			}else{
				var iframe=$container.find("iframe")[0];
			}
			
			var win = iframe.contentWindow;
			self.iframe = iframe;
			self._dom = iframe.contentDocument || iframe.contentWindow.document;
			win.focus();
		},200);
		
		return 1;
	},
	
	ok: function(eid, Data){
		var dom=this._dom;
		//过滤
		content = this.clean(dom.body.innerHTML);
		if(dom && !/^<p>&nbsp;<\/p>$/i.test(content)) Data.insertHtml(content);
		return 1;
	},

	clean:function(html){
		//from kissy editor
		// Remove onmouseover and onmouseout events (from MS Word comments effect)
		html = html.replace(/<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3");
		html = html.replace(/<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3");

		// The original <Hn> tag send from Word is something like this: <Hn style="margin-top:0px;margin-bottom:0px">
		html = html.replace(/<H(\d)([^>]*)>/gi, "<h$1>");

		// Word likes to insert extra <font> tags, when using MSIE. (Wierd).
		html = html.replace(/<(H\d)><FONT[^>]*>([\s\S]*?)<\/FONT><\/\1>/gi, "<$1>$2<\/$1>");
		html = html.replace(/<(H\d)><EM>([\s\S]*?)<\/EM><\/\1>/gi, "<$1>$2<\/$1>");

		// Remove <meta xx...>
		html = html.replace(/<meta[^>]*>/ig, "");

		// Remove <link rel="xx" href="file:///...">
		html = html.replace(/<link rel="\S+" href="file:[^>]*">/ig, "");

		// Remove <!--[if gte mso 9|10]>...<![endif]-->
		html = html.replace(/<!--\[if gte mso [0-9]{1,2}\]>[\s\S]*?<!\[endif\]-->/ig, "");

		// Remove <style> ...mso...</style>
		html = html.replace(/<style>[\s\S]*?mso[\s\S]*?<\/style>/ig, "");

		// Remove lang="..."
		html = html.replace(/ lang=".+?"/ig, "");

		// Remove <o:p></o:p>
		html = html.replace(/<o:p><\/o:p>/ig, "");

		// Remove class="MsoNormal"
		html = html.replace(/ class="Mso.+?"/ig, "");
		
		
		html = html.replace(/ mso-spacerun: 'yes'/ig, "");
		//html = html.replace(/ class=\w+?/ig, "");
		
		/*
		html = html.replace(/<\/?SPAN[^>]*>/gi, "");
		html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3");
		html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3");
		html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");
		html = html.replace(/<\\?\?xml[^>]*>/gi, "");
		html = html.replace(/<\/?\w+:[^>]*>/gi, "");
		html = html.replace(/(&nbsp;)+/gi, " ");

		html = html.replace(/<(style|xml).*?>[\s\S]*?<\/\1>/gi, '');
		html = html.replace(/<!--[\s\S]*?-->/gi, '');
		html = html.replace(/<(link|meta)[^>]*?>/gi, '');
		html = html.replace(/<img[^>]*?>/gi, '');
		*/

		return html;
	}
});


E.plugin("Save", {
	click:function($btn, dom, eid){
		var History = E.mod("History");
		History && History.add(dom, eid);
		return 1;
	}
});

//根据内容自动调整编辑区域的高度
E.plugin("AutoHeight",function(eid){
	var H=0, //内容的高度
	iframe=E.iframes[eid], option=E.options[eid];
	if (!iframe){return false;}
	
	if (!$.IE){
		H = iframe.contentDocument.body.offsetHeight + 20;
	}else if($.IE) {//IE
		H = iframe.Document.body.scrollHeight + 20;
	}else{
		return false;
	}
	
	H = option.height > H ? option.height : H;
	iframe.style.height = H+'px'; //Safari Chrame
	iframe.height = H; // IE6
	
	option['maxTops']=E.tops[eid] + H;
	var Editor=$('#'+eid);
	Editor.find('div.editor_content').height(H);
	
	/*
	animate  会导致编辑器光标位置丢失，还是使用上面的方式比较好
	
	if($.IE6){
		Editor.find('div.editor_content').height(H);
	}else{
		//如果不是IE6则使用滑动效果
		Editor.find('div.editor_content').animate({height:H}, 500);
	}
	*/
	return 1;
});

//将工具栏固定在浏览器窗口顶部，由 AutoHeight 调用，和 AutoHeight 结合使用
E.plugin("AutoFixedToolbar", function(eid){
	var option=E.options[eid],scrollTop = $(document).scrollTop(), $bar=$("#"+eid+"_toolbar");
	
	if(scrollTop > option['maxTops']){
		//当工具栏超过编辑器区域最下面的边时，则还原工具栏
		$bar.removeClass("fixed");
		return;
	}
	
	if(scrollTop > E.tops[eid]){
		$bar.addClass("fixed");
	}else{
		$bar.removeClass("fixed");
	}
	
	if($.IE6){
		$bar.css('top',scrollTop);
	}
});

})($.editor);